package com.ruoyi.exam.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.exam.domain.entity.ExamPaper;
import com.ruoyi.exam.domain.entity.ExamPaperQuestion;
import com.ruoyi.exam.mapper.ExamPaperMapper;
import com.ruoyi.exam.mapper.ExamPaperQuestionMapper;
import com.ruoyi.exam.service.IExamPaperService;

/**
 * 考试试卷Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-17
 */
@Service
public class ExamPaperServiceImpl implements IExamPaperService {
    @Autowired
    private ExamPaperMapper examPaperMapper;

    @Autowired
    private ExamPaperQuestionMapper examPaperQuestionMapper;

    /**
     * 查询考试试卷
     *
     * @param id 考试试卷主键
     * @return 考试试卷
     */
    @Override
    public ExamPaper selectExamPaperById(Long id) {
        ExamPaper examPaper = examPaperMapper.selectExamPaperById(id);
        if (StringUtils.isNotNull(examPaper)) {
            ExamPaperQuestion examPaperQuestion = new ExamPaperQuestion();
            examPaperQuestion.setExamPaperId(examPaper.getId());
            List<ExamPaperQuestion> selectExamPaperQuestionList = examPaperQuestionMapper
                    .selectExamPaperQuestionList(examPaperQuestion);
            examPaper.setExamPaperQuestions(selectExamPaperQuestionList);
        }
        return examPaper;
    }

    /**
     * 查询考试试卷列表
     *
     * @param examPaper 考试试卷
     * @return 考试试卷
     */
    @Override
    @DataScope(deptAlias = "sd")
    public List<ExamPaper> selectExamPaperList(ExamPaper examPaper) {
        return examPaperMapper.selectExamPaperList(examPaper);
    }

    /**
     * 新增考试试卷
     *
     * @param examPaper 考试试卷
     * @return 结果
     */
    @Override
    @Transactional
    public int insertExamPaper(ExamPaper examPaper) {
        try {
            // 获取当前的用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            examPaper.setCreateTime(DateUtils.getNowDate());
            examPaper.setUpdateTime(DateUtils.getNowDate());
            examPaper.setDeptId(loginUser.getUser().getDeptId());
            examPaper.setCreateBy(loginUser.getUserId().toString());
            examPaper.setUpdateBy(loginUser.getUserId().toString());
            int rows = examPaperMapper.insertExamPaper(examPaper);
            insertExamPaperQuestion(examPaper);
            return rows;
        } catch (Exception e) {
            e.printStackTrace();
            // 自定义异常处理逻辑
            // 记录日志或其他处理
            // 必须抛出RuntimeException才能触发事务回滚
            throw new RuntimeException("试卷保存失败，请重试。");
        }
    }

    /**
     * 新增试卷试题信息
     *
     * @param examPaper 试卷对象
     */
    private void insertExamPaperQuestion(ExamPaper examPaper) {
        this.insertExamPaperQuestion(examPaper.getId(), examPaper.getExamPaperQuestions());
    }

    /**
     * 新增试卷试题信息
     *
     * @param examPaperId 试卷ID
     * @param questionIds 试题ID数组
     */
    private void insertExamPaperQuestion(Long examPaperId, List<ExamPaperQuestion> examPaperQuestions) {
        if (StringUtils.isNotEmpty(examPaperQuestions)) {
            // 新增用户与角色管理
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Date now = DateUtils.getNowDate();
            long sort = 1;
            // 遍历examPaperQuestions列表
            for (ExamPaperQuestion examPaperQuestion : examPaperQuestions) {
                examPaperQuestion.setExamPaperId(examPaperId);
                examPaperQuestion.setId(null);
                examPaperQuestion.setCreateBy(loginUser.getUserId().toString());
                examPaperQuestion.setCreateTime(now);
                examPaperQuestion.setUpdateBy(loginUser.getUserId().toString());
                examPaperQuestion.setUpdateTime(now);
                examPaperQuestion.setSort(sort);
                sort++;
            }
            // 先删除，再写入
            examPaperQuestionMapper.deleteExamPaperQuestionByPaperId(examPaperId);
            examPaperQuestionMapper.batchInsertExamPaperQuestion(examPaperQuestions);
        }
    }

    /**
     * 修改考试试卷
     *
     * @param examPaper 考试试卷
     * @return 结果
     */
    @Override
    @Transactional
    public int updateExamPaper(ExamPaper examPaper) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        examPaper.setCreateBy(loginUser.getUserId().toString());
        examPaper.setUpdateTime(DateUtils.getNowDate());
        examPaper.setDeptId(loginUser.getUser().getDeptId());
        // 删除关联的题目列表
        examPaperQuestionMapper.deleteExamPaperQuestionByPaperId(examPaper.getId());
        // 重新插入关联的题目列表
        insertExamPaperQuestion(examPaper);
        // 更新试卷主表
        return examPaperMapper.updateExamPaper(examPaper);
    }

    /**
     * 批量删除考试试卷
     *
     * @param ids 需要删除的考试试卷主键
     * @return 结果
     */
    @Override
    public int deleteExamPaperByIds(Long[] ids) {
        return examPaperMapper.deleteExamPaperByIds(ids);
    }

    /**
     * 删除考试试卷信息
     *
     * @param id 考试试卷主键
     * @return 结果
     */
    @Override
    public int deleteExamPaperById(Long id) {
        return examPaperMapper.deleteExamPaperById(id);
    }

    @Override
    public boolean checkExamPaperNameUnique(ExamPaper examPaper) {
        ExamPaper checkExamPaperNameUnique = examPaperMapper.checkExamPaperNameUnique(examPaper.getName());
        if (StringUtils.isNotNull(checkExamPaperNameUnique)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
